package group.igfd.manager.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import group.igfd.manager.biz.dao.PublishBuyersDao;
import group.igfd.manager.biz.entity.PublishBuyersEntity;
import group.igfd.manager.biz.model.BuyerStatisticsDO;
import group.igfd.manager.biz.model.BuyerStatisticsModel;
import group.igfd.manager.biz.model.ExcelData;
import group.igfd.manager.biz.model.PublisherBuyerModel;
import group.igfd.manager.biz.service.BrandsService;
import group.igfd.manager.biz.service.CategoriesService;
import group.igfd.manager.biz.service.PublishBuyersService;
import group.igfd.manager.biz.service.UsersService;
import group.igfd.manager.biz.utils.ExportExcelUtils;
import group.igfd.manager.biz.utils.NumberFormatUtil;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


@Service("publishBuyersService")
public class PublishBuyersServiceImpl extends ServiceImpl<PublishBuyersDao, PublishBuyersEntity> implements PublishBuyersService {

    private Logger logger = LoggerFactory.getLogger(PublishBuyersServiceImpl.class);

    @Autowired
    private BrandsService brandsService;
    @Autowired
    private CategoriesService categoriesService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private PublishBuyersDao publishBuyersDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Map<String, Object> map = new HashMap<>();
        if (!ObjectUtils.isEmpty(params.get("brandId"))) {
            map.put("brand", params.get("brandId").toString());
        }
        if (!ObjectUtils.isEmpty(params.get("uid"))) {
            map.put("uid", params.get("uid").toString());
        }
        if (!ObjectUtils.isEmpty(params.get("categoryId"))) {
            map.put("categoryId", params.get("categoryId").toString());
        }
        if (!ObjectUtils.isEmpty(params.get("category2Id"))) {
            map.put("category2Id", params.get("category2Id").toString());
        }
        if (!ObjectUtils.isEmpty(params.get("title"))) {
            map.put("title", "%" + params.get("title").toString() + "%");

        }
        if (!ObjectUtils.isEmpty(params.get("minDt"))) {
            String minDt = params.get("minDt") + "";
            map.put("minDt", minDt + " 00:00:00");
        }
        if (!ObjectUtils.isEmpty(params.get("maxDt"))) {
            String minDt = params.get("maxDt") + "";
            map.put("maxDt", minDt + " 23:59:59");
        }

        //计算limit分页
        int pageNum = Integer.parseInt(params.get("page").toString());
        int limit = Integer.parseInt(params.get("limit").toString());
        int startNum = (pageNum - 1) * limit;//分页开始index
        map.put("startNum", startNum);
        map.put("endNum", limit);
        List<PublishBuyersEntity> publishBuyersEntityList = publishBuyersDao.getPublishBuyersByParms(map);
        int count = publishBuyersDao.getPublishBuyersByParmsCount(map);
        Page<PublisherBuyerModel> newPage = new Page<>();

        newPage.setTotal(count);
        newPage.setCurrent(pageNum);
        newPage.setSize(limit);
        List<PublisherBuyerModel> list = new ArrayList<>();
        if (publishBuyersEntityList != null && publishBuyersEntityList.size() > 0) {
            for (PublishBuyersEntity entity : publishBuyersEntityList) {
                PublisherBuyerModel model = new PublisherBuyerModel();
                model.setId(entity.getId());
                model.setNickName(usersService.getNickName(entity.getUid()));
                model.setTitle(entity.getTitle());
                if (entity.getTitlePicture().endsWith("def")) {
                    model.setTitlePic(entity.getTitlePicture().substring(0, entity.getTitlePicture().lastIndexOf("/")) + "/admin");
                } else {
                    model.setTitlePic(entity.getTitlePicture());
                }
                model.setBrand(brandsService.getBrandName(entity.getBrand()));
                model.setType(categoriesService.getCategoryName(entity.getType()));
                model.setSku(entity.getSku());
                model.setColor(entity.getColor());
                model.setSize(entity.getSize());
                model.setSex(entity.getSex());

                Double priceEur = entity.getEurPrice();
                Double priceRmb = entity.getPrice();
                if (null != priceRmb) {
                    model.setPrice("CNY: " + priceRmb.intValue());
                }
                if (null != priceEur) {
                    model.setPrice("EUR: " + priceEur.intValue());
                }
                if (null != entity.getDiscount()) {
                    model.setDiscount(NumberFormatUtil.getPercent(entity.getDiscount()));
                }
                if (null != entity.getCreatedAt())
                    model.setPublishTime(DateUtils.format(entity.getCreatedAt(), DateUtils.DATE_TIME_PATTERN));
                if (null != entity.getDay())
                    model.setReceiveTime(entity.getDay() + " 天");
                list.add(model);
            }
        }
        newPage.setRecords(list);
        return new PageUtils(newPage);
    }

    /**
     * 分页
     *
     * @param begin
     * @param end
     * @param list
     * @return
     */
    public List setListPageDate(Integer begin, Integer end, List list) {
        List pageList = null;
        if (list.size() > 0 && !StringUtils.isEmpty(begin) && !StringUtils.isEmpty(end)) {
            Integer maxSize = begin + end;
            Integer dataSize = list.size();
            if (maxSize < dataSize) {
                pageList = list.subList(begin, maxSize);
            } else {
                pageList = list.subList(begin, list.size());
            }
        }
        return pageList;
    }

//    @Override
//    public PageUtils queryPage(Map<String, Object> params) {
//
//        EntityWrapper<PublishBuyersEntity> ew = new EntityWrapper<>();
//        if(!ObjectUtils.isEmpty(params.get("brandId"))){
//            ew.eq("brand", params.get("brandId"));
//        }
//        if(!ObjectUtils.isEmpty(params.get("uid"))){
//            ew.eq("uid", params.get("uid"));
//        }
//        if(!ObjectUtils.isEmpty(params.get("categoryId"))){
//            ew.eq("type", params.get("categoryId"));
//        }
//        if(!ObjectUtils.isEmpty(params.get("title"))){
//            ew.like(true,"title", params.get("title")+"");
//
//        }
//        if(!ObjectUtils.isEmpty(params.get("minDt"))){
//            String minDt = params.get("minDt")+"";
//            ew.ge("created_at", minDt +" 00:00:00");
//        }
//        if(!ObjectUtils.isEmpty(params.get("maxDt"))){
//            String minDt = params.get("maxDt")+"";
//            ew.le("created_at", minDt +" 23:59:59");
//        }
//        ew.isNull("deleted_at");
//        ew.orderBy("created_at", false);
//        Page<PublishBuyersEntity> page = this.selectPage(
//                new Query<PublishBuyersEntity>(params).getPage(),
//                ew
//        );
//        Page<PublisherBuyerModel> newPage = new Page<>();
//
//        newPage.setTotal(page.getTotal());
//        newPage.setCurrent(page.getCurrent());
//        newPage.setSize(page.getSize());
//        List<PublisherBuyerModel> list = new ArrayList<>();
//        if(page != null && page.getRecords() != null && page.getRecords().size() > 0){
//            for(PublishBuyersEntity entity : page.getRecords()){
//                PublisherBuyerModel model = new PublisherBuyerModel();
//                model.setId(entity.getId());
//                model.setNickName(usersService.getNickName(entity.getUid()));
//                model.setTitle(entity.getTitle());
//                model.setTitlePic(entity.getTitlePicture());
//                model.setBrand(brandsService.getBrandName(entity.getBrand()));
//                model.setType(categoriesService.getCategoryName(entity.getType()));
//                model.setSku(entity.getSku());
//                model.setColor(entity.getColor());
//                model.setSize(entity.getSize());
//                model.setSex(entity.getSex());
//
//                Double priceEur = entity.getEurPrice();
//                Double priceRmb = entity.getPrice();
//                if(null != priceRmb){
//                    model.setPrice("CNY: " + priceRmb.intValue());
//                }
//                if(null != priceEur){
//                    model.setPrice("EUR: " + priceEur.intValue());
//                }
//                if(null != entity.getDiscount()){
//                    model.setDiscount(NumberFormatUtil.getPercent(entity.getDiscount()));
//                }
//                if(null != entity.getCreatedAt())
//                    model.setPublishTime(DateUtils.format(entity.getCreatedAt(), DateUtils.DATE_TIME_PATTERN));
//                if(null != entity.getDay())
//                    model.setReceiveTime(entity.getDay()+" 天");
//                list.add(model);
//            }
//        }
//        newPage.setRecords(list);
//        return new PageUtils(newPage);
//    }

    @Override
    public PageUtils queryStatistics(Map<String, Object> params) {
        int currPage = 1;
        if (params.get("page") != null) {
            currPage = Integer.parseInt((String) params.get("page"));
        }
        int limit = 10;
        if (params.get("limit") != null) {
            limit = Integer.parseInt((String) params.get("limit"));
        }
        int offset = (currPage - 1) * limit;
        Page<BuyerStatisticsModel> page = new Page();
        page.setCurrent(currPage);

        page.setSize(limit);

        BuyerStatisticsDO query = new BuyerStatisticsDO();
        query.setOffset(offset);
        query.setSize(limit);
        if (!ObjectUtils.isEmpty(params.get("uid"))) {
            query.setUid(params.get("uid") + "");
        }
        String yyyyMM = (String) params.get("dt");
        if (ObjectUtils.isEmpty(yyyyMM)) {
            yyyyMM = DateUtils.format(new Date(), "yyyy-MM");
        }
        Calendar calendar = Calendar.getInstance();
        int year = Integer.valueOf(yyyyMM.substring(0, 4));
        int month = Integer.valueOf(yyyyMM.substring(5));
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String minDate = DateUtils.format(calendar.getTime(), "yyyy-MM-dd") + " 00:00:00";
        calendar.add(Calendar.MONTH, 1);
        String maxDate = DateUtils.format(calendar.getTime(), "yyyy-MM-dd") + " 00:00:00";

        query.setMinDate(minDate);
        query.setMaxDate(maxDate);
        int total = baseMapper.getStatisticsListCount(query);
        List<BuyerStatisticsModel> list = baseMapper.getStatisticsList(query);
        handle(yyyyMM, list);
        page.setTotal(total);
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public void export(String uid, String dt, HttpServletResponse response) throws IOException {
        BuyerStatisticsDO query = new BuyerStatisticsDO();
        if (!StringUtils.isEmpty(uid))
            query.setUid(uid);
        String yyyyMM = dt;
        if (ObjectUtils.isEmpty(yyyyMM)) {
            yyyyMM = DateUtils.format(new Date(), "yyyy-MM");
        }
        Calendar calendar = Calendar.getInstance();
        int year = Integer.valueOf(yyyyMM.substring(0, 4));
        int month = Integer.valueOf(yyyyMM.substring(5));
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String minDate = DateUtils.format(calendar.getTime(), "yyyy-MM-dd") + " 00:00:00";
        calendar.add(Calendar.MONTH, 1);
        String maxDate = DateUtils.format(calendar.getTime(), "yyyy-MM-dd") + " 00:00:00";

        query.setMinDate(minDate);
        query.setMaxDate(maxDate);
        List<BuyerStatisticsModel> list = baseMapper.getExportList(query);

        handle(yyyyMM, list);

        ExcelData<BuyerStatisticsModel> data = new ExcelData();
        data.setName(yyyyMM + "月 买手统计信息");
        data.setTitles(Arrays.asList("序号", "买手昵称", "买手手机号", "当月发布商品数量", "订单总价格", "订单总数量", "佣金", "买手发布商品总数量"));
        data.setRows(list);
        try {
            ExportExcelUtils.exportExcel(response, "yyyy-MM买手商品统计", data);
        } catch (Exception e) {
            logger.error("导出文件失败", e);
        }
    }


    private void handle(String yyyyMM, List<BuyerStatisticsModel> list) {
        list.stream().forEach(model -> {
            EntityWrapper<PublishBuyersEntity> ew = new EntityWrapper<>();
            ew.eq("uid", model.getUid());
            int count = this.selectCount(ew);
            model.setProductTotalCount(count);
        });
        if (isCurrentMonth(yyyyMM)) {
            list.stream().forEach(model -> {
                double bonus = 0.00;
                if (model.getTotalPrice() > 500000) {
                    bonus = model.getTotalPrice() * 5 / 100;
                } else {
                    bonus = model.getTotalPrice() * 3 / 100;
                }
                model.setBonus(bonus);
            });
        }
    }

    private boolean isCurrentMonth(String yyyyMM) {
        String nowMonth = DateUtils.format(new Date(), "yyyy-MM");
        return nowMonth.equals(yyyyMM);
    }

}
